#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct userdata {
	char user_username[20];
	char user_password[8];
}user;

void Get_NP(user* u);
void Login(user* u);
void Fillout(user* u);
int UserdataFile_read(user* u);
void UserdataFile_write(user* u);

int main()
{
	user* u = (user*)malloc(sizeof(struct userdata));
	char choice[10];
	int i = 0;

	printf("Login or Fillout:");
	while ((choice[i] = getchar()) != '\n')
	{
		i++;
	}
	choice[i] = '\0';

	if (!strcmp("Login", choice))
	{
		Login(u);
	}
	else if (!strcmp("Fillout", choice))
	{
		Fillout(u);
	}
	else
	{
		printf("Error!\n");
	}
	return 0;
}

void Get_NP(user* u)
{
	int i = 0, j = 0;

	printf("Enter Username:");
	while ((u->user_username[i] = getchar()) != '\n')
	{
		i++;
	}
	u->user_username[i] = '\0';

	printf("Enter PassWord:");
	while ((u->user_password[j] = getchar()) != '\n')
	{
		j++;
	}
	u->user_password[j] = '\0';
}

void Login(user* u)
{
	Get_NP(u);
	if (UserdataFile_read(u))
	{
		printf("Login successful!");
	}
	else
	{
		printf("Login fail!");
	}
}

void Fillout(user* u)
{
	Get_NP(u);
	UserdataFile_write(u);
	if (UserdataFile_read(u))
	{
		printf("Fillout successful!");
	}
	else
	{
		printf("Fillout fail!");
	}
}

int UserdataFile_read(user* u)
{
	FILE* fp;
	char read_result[30];
	int check = 0;

	char protem_userdata[30];
	char protem_username[20];
	char protem_password[8];

	strcpy(protem_username, u->user_username);
	strcpy(protem_password, u->user_password);
	strcpy(protem_userdata, protem_username);

	strcat(protem_userdata, " ");
	strcat(protem_userdata, protem_password);
	strcat(protem_userdata, "\n");

	if ((fp = fopen("user_database.txt", "r")) == NULL)
	{
		printf("UserdataFile open error!\n");
		exit(0);
	}
	while (!feof(fp))
	{
		fgets(read_result, 30, fp);
		if (strcmp(read_result, protem_userdata) == 0)
		{
			check = 1;
			break;
		}
	}
	if (fclose(fp))
	{
		printf("UserdataFile close error!");
	}
	return check;
}

void UserdataFile_write(user* u)
{
	FILE* fp;

	char protem_userdata[30];
	char protem_username[20];
	char protem_password[8];

	strcpy(protem_username, u->user_username);
	strcpy(protem_password, u->user_password);
	strcpy(protem_userdata, protem_username);

	strcat(protem_userdata, " ");
	strcat(protem_userdata, protem_password);
	strcat(protem_userdata, "\n");

	if ((fp = fopen("user_database.txt", "a")) == NULL)
	{
		printf("UserdataFile open error!\n");
		exit(0);
	}

	fputs(protem_userdata, fp);

	if (fclose(fp))
	{
		printf("UserdataFile close error!");
		exit(0);
	}
}
